package org.OpenGeoPortal.Geoserver.Util;

import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.net.InetAddress;
import org.OpenGeoPortal.Geoserver.REST.GsREST;

public class gsUtils {

	private static String[] CoverageStores = new String[900000];
	private static int saxI = 0;

	public static boolean isLayerPublished(String xmlString, String layerName) {
		if (xmlString.contains(layerName))
			return true;
		else
			return false;
	}
	
	public static boolean isEntryInTilecache(String path2file, String layerName) {
		boolean inThere = false;
		
		try {
		    FileInputStream fstream = new FileInputStream(path2file);
		    DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
		    String strLine;

		    //Read File Line By Line
			    while ((strLine = br.readLine()) != null)   {
			      if (strLine.contains("["+layerName.toUpperCase()+"]")) {
			    	  inThere = true;
			    	  break;
			      }
			    }
		    in.close();
		    
		} catch (Exception e) {
		      System.err.println("Error: " + e.getMessage());
		}
		    
	  return inThere;
	  
	}
	
	public static boolean appendToTilecacheConfigFile(String coverageStoreName, String owner, String layerName, String bbox) {

		boolean appended = false;
		layerName = layerName.toUpperCase();

		String servername = "dixon.hul.harvard.edu";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			if (addr.getHostName() != null)
				servername = addr.getHostName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/* Add necessary information to the tilecache.cfg
		 * In dev the file is /var/www/cgi-bin/tilecache/tilecache.cfg
		 * In prd the file is /var/www/cgi-bin/tilecache.cfg
		 */
		String path2file = "/var/www/cgi-bin/tilecache/tilecache.cfg";
		if (servername.contains("dixon"))
			path2file = "/var/www/cgi-bin/tilecache.cfg";

		// Does the entry exist in tilecache.cfg?
		// If it is alreay there then there is no work to do here
		if (isEntryInTilecache(path2file, layerName))
			return true;
		
		// Add the data
		String tileCFGTxt = "["+layerName+"]\n";
		tileCFGTxt += "type=WMSLayer\n";
		tileCFGTxt += "layers="+coverageStoreName+":"+owner+"."+layerName+"\n";
		tileCFGTxt += "url=http://"+servername+":8080/geoserver/wms?transparent=true\n";
		tileCFGTxt += "extension=png\n";
		tileCFGTxt += "spherical_mercator=yes\n";
		tileCFGTxt += "srs=EPSG:900913\n\n";
		//tileCFGTxt += bbox+"\n\n";

		try {
		    FileWriter fstream = new FileWriter(path2file,true);
	        BufferedWriter out = new BufferedWriter(fstream);
		    out.write(tileCFGTxt);
		    out.close();
		} catch (Exception e) {
 	        System.err.println("Error: " + e.getMessage());
		}
			    
		return appended;

	}
	
	public static boolean isCoverageStoreExists(String gsCsName, String gsWorkspace) {
		boolean exists = false;

		String servername = "dixon.hul.harvard.edu";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			if (addr.getHostName() != null)
				servername = addr.getHostName();
		} catch (Exception e) {
			e.printStackTrace();
		}

		GsREST myObject = new GsREST("http://"+servername+":8080/geoserver","xx","xx");
		String junk = "";
		
		try {
			
			junk = myObject.getCoveragestoreNames(gsWorkspace); // "cite"

			InputStream is = new ByteArrayInputStream(junk.getBytes("UTF-8"));
  	        SAXParserFactory factory = SAXParserFactory.newInstance();
		    SAXParser saxParser = factory.newSAXParser();

		    DefaultHandler handler = new DefaultHandler() {
		      boolean name = false;

		      public void startElement(String uri, String localName,
		          String qName, Attributes attributes)
		          throws SAXException {
		        if (qName.equalsIgnoreCase("name")) {
		          name = true;
		        }
		      }

		      public void characters(char ch[], int start, int length)
		          throws SAXException {
		       if (name) {
		      	  String _temp_ = new String(ch, start, length);
		       	  CoverageStores[saxI] = _temp_.toString();
		       	  saxI++;
		           name = false;
		         }
		       }
		      };

		      saxParser.parse(is, handler);

		    } catch (Exception e) {
		      e.printStackTrace();
		    }
		
		for (int x=0;x<CoverageStores.length;x++) {
		  if (CoverageStores[x] !=null && !CoverageStores[x].equals(""))
		    if (CoverageStores[x].equalsIgnoreCase(gsCsName))
			  return true;
		}
		CoverageStores = null;
		return exists;
	}
	
	
	public static String[] getCoverageStoreNames(String gsWorkspace) {

		saxI = 0;
		
		String servername = "dixon.hul.harvard.edu";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			if (addr.getHostName() != null)
				servername = addr.getHostName();
		} catch (Exception e) {
			e.printStackTrace();
		}

		GsREST myObject = new GsREST("http://"+servername+":8080/geoserver","xx","xx");
		String junk = "";
		
		try {
			
			junk = myObject.getCoveragestoreNames(gsWorkspace); // "cite"

			InputStream is = new ByteArrayInputStream(junk.getBytes("UTF-8"));
  	        SAXParserFactory factory = SAXParserFactory.newInstance();
		    SAXParser saxParser = factory.newSAXParser();

		    DefaultHandler handler = new DefaultHandler() {
		      boolean name = false;

		      public void startElement(String uri, String localName,
		          String qName, Attributes attributes)
		          throws SAXException {
		        if (qName.equalsIgnoreCase("name")) {
		          name = true;
		        }
		      }

		      public void characters(char ch[], int start, int length)
		          throws SAXException {
		       if (name) {
		      	  String _temp_ = new String(ch, start, length);
		       	  CoverageStores[saxI] = _temp_.toString();
		       	  saxI++;
		           name = false;
		         }
		       }
		      };

		      saxParser.parse(is, handler);

		    } catch (Exception e) {
		      e.printStackTrace();
		    }
		  
		CoverageStores = null;
		return CoverageStores;
	}

}
